package com.cbtx.tablet.ui

import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.text.method.ScrollingMovementMethod
import android.view.MotionEvent
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.cbtx.networklib.ContextManager
import com.cbtx.tablet.App
import com.cbtx.tablet.BuildConfig
import com.cbtx.tablet.R
import com.cbtx.tablet.constant.HttpConstant
import com.cbtx.tablet.device.IMachine
import com.cbtx.tablet.device.MachineFactory
import com.cbtx.tablet.dialog.UnbindDialog
import com.cbtx.utils.DeviceUtil
import com.cbtx.utils.NetWorkUtil
import com.cbtx.utils.zxing.ZxingUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_device_info.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

class DeviceInfoActivity : AbsBaseActivity() {

    var lastClickTime: Long = System.currentTimeMillis()
    private var timeDispose: Disposable? = null
    private var storeInfoDispose: Disposable? = null

    override fun layoutId(): Int = R.layout.activity_device_info


    override fun initView(savedInstanceState: Bundle?) {
        val sf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        mips_info.text = sf.format(Date())

        btn_show_qr_code.setOnClickListener {
            lastClickTime = System.currentTimeMillis()
            val qRCodeDialog = UnbindDialog(this, ubindQrCode())
            qRCodeDialog.show()
        }

        firmware_des.movementMethod = ScrollingMovementMethod.getInstance()
        firmware_des.text = Build.DISPLAY

        when (NetWorkUtil.getNetWorkState(this)) {
            0 -> network_status_des.text = getString(R.string.register_qr_gprs)
            1 -> network_status_des.text = getString(R.string.register_qr_wifi)
            2 -> network_status_des.text = getString(R.string.register_qr_eth)
            else -> network_status_des.text = getString(R.string.register_qr_none)
        }

        if (NetworkUtils.isConnected()) {
            terminal_status_des.text = "在线"
            terminal_status_des.setTextColor(Color.parseColor("#0BD728"))
        } else {
            terminal_status_des.text = "离线"
            terminal_status_des.setTextColor(Color.parseColor("#F50F0F"))
        }

        mac_des.text = DeviceUtil.getMac(this)

        authorization_info_des.text = "已授权"

        terminal_serial_des.text = App.androidId

        software_version_des.text = versionName(this)

        ip_add_des.text = NetworkUtils.getIPAddress(true)

        btn_close.setOnClickListener {
            finish()
        }

        position_info_des.movementMethod = ScrollingMovementMethod.getInstance()
        position_info_des.text =
            SPUtils.getInstance().getString("storeName") + "/" + SPUtils.getInstance().getString("roomCode")

        // 30秒检测一次是否回到主页面（10分钟未操作即回到主页）
        timeDispose = Observable.interval(0, 20, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (System.currentTimeMillis() - lastClickTime > 1000 * 60 * 10) { // 十分钟自动关闭
                    timeDispose?.apply {
                        if (!this.isDisposed) {
                            this.dispose()
                        }
                    }
                    finish()
                }
            }

        storeInfoDispose = Observable.interval(0, 20, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                getStoreInfo()
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        storeInfoDispose?.apply {
            if (!this.isDisposed) {
                this.dispose()
            }
        }
    }

    private fun getStoreInfo() {
        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .getStoreInfo()
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e(it.toString())
                },
                onNext = {
                    SPUtils.getInstance().put("storeName", it.data?.storeName)
                    SPUtils.getInstance().put("roomCode", it.data?.roomCode)
                    SPUtils.getInstance().put("storeId", it.data?.storeId!!)
                    position_info_des.text = it.data?.storeName + "/" + it.data?.roomCode
                }
            )
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        lastClickTime = System.currentTimeMillis()
        return super.onTouchEvent(event)
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun ubindQrCode(): Bitmap? {
        val wh: Int = ContextManager.getContext().resources.getDimensionPixelSize(R.dimen.dp_400)
        val iMachine: IMachine =
            MachineFactory.getAutoCreate(App.instance)

        var url = if (BuildConfig.DEBUG) {
            ContextManager.getContext().getString(
                R.string.register_qr,
                "t.mj.linkzl.com",
                if (TextUtils.isEmpty(DeviceUtil.getSerial(this))) "" else DeviceUtil.getSerial(this),
                MachineFactory.getAutoCreate(ContextManager.getContext()).uniqueDeviceCode,
                "INTERACTIVE",
                iMachine.localMac,
                iMachine.model
            )
        } else {
            ContextManager.getContext().getString(
                R.string.register_qr,
                "ad.mjcmkj.com",
                if (TextUtils.isEmpty(DeviceUtil.getSerial(this))) "" else DeviceUtil.getSerial(this),
                MachineFactory.getAutoCreate(ContextManager.getContext()).uniqueDeviceCode,
                "INTERACTIVE",
                iMachine.localMac,
                iMachine.model
            )
        }

        return ZxingUtils.createQRCode(
            url,
            wh,
            BitmapFactory.decodeResource(resources, R.mipmap.ic_logo_qr_code)
        )
    }

    fun versionName(context: Context): String {
        val manager = context.packageManager
        var name = ""
        try {
            val info = manager.getPackageInfo(context.packageName, 0)
            name = info.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return name
    }

}